package com.aracky.common.util.wxutil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aracky.common.exception.BaseException;
import com.aracky.common.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zengzhiping
 * @ClassName: WxMsgUtil
 * @Description: 微信消息工具类
 * @date 2022/07/26 11:08
 */
@Component
@Slf4j
public class WxMsgUtil {

    private static Logger logger = LoggerFactory.getLogger(WxMsgUtil.class);

    @Autowired
    private AuthTokenUtil authTokenUtil;


    @Value("${wx.config.agentId}")
    private String agentId;

    /**
     * 发送卡片消息
     *
     * @param touser      接收人
     * @param title       标题
     * @param description 描述
     * @param msgUrl      卡片雄安锡跳转地址
     * @return
     */
    public String sendCardMessage(String touser, String title, String description, String msgUrl) {
        logger.info(" 标题：{},发送人：{},描述：{},地址：{}" + title, touser, description, msgUrl);

        //获取token
        String accessToken = authTokenUtil.getAccessToken();
        String sendUrl = WxUrl.SEND_URL + accessToken;
        //构造参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("touser", touser);
        paramMap.put("msgtype", "textcard");
        paramMap.put("agentid", agentId);

        Map<String, Object> textMap = new HashMap<>();
        textMap.put("title", title);
        textMap.put("description", description);
        textMap.put("url", msgUrl);
        paramMap.put("textcard", textMap);
        paramMap.put("btntxt", "查看详情");
        String body = HttpUtil.sendPostHttps(sendUrl, paramMap);
        JSONObject result = JSON.parseObject(body);
        if (0 != result.getInteger("errcode")) {
            log.error("错误消息：{}", result);
            //消息发送失败
            throw new BaseException("推送微信消息失败...");
        }
        return result.getString("msgid");
    }


}
